package cn.zptc.dao.impl;

import cn.zptc.dao.LinkDao;
import cn.zptc.utils.C3p0Util;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.ResultSet;
import java.sql.SQLException;

public class LinkDaoImpl implements LinkDao {
    /**
     * 根据链接地址查询链接地址的id
     *
     * @param linkUrl
     * @return 链接地址的id
     */
    @Override
    public int selectLinkUrlCount(String linkUrl) throws SQLException {
        QueryRunner runner = new QueryRunner(C3p0Util.getDataSource());
        String sql="SELECT\n" +
                "  count(id)\n" +
                "FROM\n" +
                "  `t_link`\n" +
                "WHERE\n" +
                "   `link_url`=?";
        return runner.query(sql, rs -> {rs.next();return rs.getInt(1);}, linkUrl);
    }

    /**
     * 根据链接地址查询链接的id，如果存在，返回id，如果不存在返回-1
     *
     * @param linkUrl
     * @return
     */
    @Override
    public int selectLinkId(String linkUrl) throws SQLException {
        QueryRunner runner = new QueryRunner(C3p0Util.getDataSource());
        String sql="SELECT\n" +
                "  id\n" +
                "FROM\n" +
                "  `t_link`\n" +
                "WHERE\n" +
                "   `link_url`=?";
        return runner.query(sql, rs -> rs.next() ? rs.getInt(1) : -1, linkUrl);
    }

    @Override
    public int insert(String linkUrl) throws SQLException {
        QueryRunner runner = new QueryRunner(C3p0Util.getDataSource());
        String sql="INSERT INTO `t_link` (`link_url`) VALUES (?)";
        return runner.insert(sql, rs -> rs.next() ? rs.getInt(1) : -1, linkUrl);
    }
}
